import { PrintUtils } from '../utils/printUtils.js'

// 内容分页处理函数
export function usePagination(formatSettings) {
  
  function splitContentToLines(html) {
    const container = PrintUtils.createHiddenContainer(formatSettings)
    
    // 如果内容是纯文本（包含换行符），先将其转换为HTML格式
    let processedHtml = html
    if (!html.includes('<p>') && !html.includes('<div>') && !html.includes('<h3>')) {
      // 纯文本内容，按换行符分割并包装成段落
      const lines = html.split('\n')
      processedHtml = lines.map(line => 
        line.trim() === '' ? '<p>&nbsp;</p>' : `<p>${line}</p>`
      ).join('')
    }
    
    const tempDiv = document.createElement('div')
    tempDiv.innerHTML = processedHtml
    
    const lines = []
    
    // 遍历所有子节点
    tempDiv.childNodes.forEach(node => {
      if (node.nodeType === 1 && node.tagName === 'P') {
        const pContent = node.innerHTML || ''
        if (pContent.trim() === '' || pContent === '&nbsp;') {
          // 空段落，添加一个空行
          lines.push({ content: '&nbsp;', isFirstLineOfParagraph: false, isTitle: false })
        } else {
          // 将段落内容拆分成多行
          const paragraphLines = splitParagraphIntoLines(pContent, container)
          paragraphLines.forEach((lineContent, index) => {
            lines.push({
              content: lineContent,
              isFirstLineOfParagraph: index === 0,
              isTitle: false
            })
          })
        }
      } else if (node.nodeType === 1 && node.tagName === 'H3') {
        // 标题处理
        lines.push({ content: node.outerHTML, isFirstLineOfParagraph: false, isTitle: true })
      } else if (node.nodeType === 3) {
        // 纯文本节点
        const text = node.textContent
        if (text && text.trim() !== '') {
          // 按换行符分割
          const textLines = text.split('\n')
          textLines.forEach(line => {
            if (line.trim()) {
              const paragraphLines = splitParagraphIntoLines(line, container)
              paragraphLines.forEach((lineContent, index) => {
                lines.push({
                  content: lineContent,
                  isFirstLineOfParagraph: index === 0,
                  isTitle: false
                })
              })
            } else {
              lines.push({ content: '&nbsp;', isFirstLineOfParagraph: false, isTitle: false })
            }
          })
        } else {
          lines.push({ content: '&nbsp;', isFirstLineOfParagraph: false, isTitle: false })
        }
      } else if (node.outerHTML) {
        lines.push({ content: node.outerHTML, isFirstLineOfParagraph: false, isTitle: false })
      }
    })
    
    // 如果没有内容，创建一个空行作为起始
    if (lines.length === 0) {
      lines.push({ content: '&nbsp;', isFirstLineOfParagraph: false, isTitle: false })
    }
    
    return lines
  }

  // 新增函数：将段落内容拆分成适合页面宽度的多行
  function splitParagraphIntoLines(content, measureContainer) {
    if (!content || content.trim() === '') {
      return ['&nbsp;']
    }

    // 创建一个临时div来测量文本宽度
    const testDiv = document.createElement('div')
    testDiv.style.fontSize = `${formatSettings.fontSize}pt`
    testDiv.style.lineHeight = formatSettings.lineHeight
    testDiv.style.fontFamily = formatSettings.fontFamily
    testDiv.style.width = measureContainer.style.width
    testDiv.style.textIndent = `${formatSettings.paragraphIndent}em`
    testDiv.style.wordWrap = 'break-word'
    testDiv.style.whiteSpace = 'pre-wrap'
    testDiv.innerHTML = content
    
    measureContainer.appendChild(testDiv)
    
    // 计算实际渲染的行数
    const lineHeight = parseFloat(formatSettings.fontSize) * parseFloat(formatSettings.lineHeight) * 1.33
    const totalHeight = testDiv.offsetHeight
    const actualLineCount = Math.round(totalHeight / lineHeight)
    
    measureContainer.removeChild(testDiv)
    
    if (actualLineCount <= 1) {
      return [content]
    }
    
    // 如果是多行，则需要模拟浏览器的换行行为
    // 使用Canvas或者更精确的方法来测量文本宽度
    const lines = []
    const text = content.replace(/<[^>]*>/g, '') // 移除HTML标签进行测量
    const availableWidth = parseFloat(measureContainer.style.width)
    const indentWidth = parseFloat(formatSettings.paragraphIndent) * parseFloat(formatSettings.fontSize) * 0.5 // 估算缩进宽度
    
    // 创建Canvas来精确测量文本宽度
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    ctx.font = `${formatSettings.fontSize}pt ${formatSettings.fontFamily}`
    
    let currentLine = ''
    let currentWidth = 0
    let isFirstLine = true
    const maxWidth = availableWidth - (isFirstLine ? indentWidth : 0)
    
    for (let i = 0; i < text.length; i++) {
      const char = text[i]
      const charWidth = ctx.measureText(char).width
      
      if (currentWidth + charWidth > maxWidth && currentLine.length > 0) {
        // 当前行已满，需要换行
        lines.push(currentLine)
        currentLine = char
        currentWidth = charWidth
        isFirstLine = false
      } else {
        currentLine += char
        currentWidth += charWidth
      }
    }
    
    // 添加最后一行
    if (currentLine) {
      lines.push(currentLine)
    }
    
    return lines.length > 0 ? lines : [content]
  }

  // 渲染单页内容，包括填充空白行
  function renderPageContent(pageLines, totalLinesPerPage) {
    const lineHeight = parseFloat(formatSettings.fontSize) * parseFloat(formatSettings.lineHeight) * 1.33
    const pageContent = []
    
    // 渲染实际内容行
    pageLines.forEach((lineData) => {
      const lineDiv = document.createElement('div')
      lineDiv.className = `record-line ${formatSettings.bottomLine}`
      lineDiv.style.minHeight = `${lineHeight}px`
      lineDiv.style.paddingBottom = '2px'
      lineDiv.style.marginBottom = formatSettings.lineSpacing || '8mm'
      lineDiv.style.lineHeight = formatSettings.lineHeight
      lineDiv.style.fontSize = `${formatSettings.fontSize}pt`
      lineDiv.style.fontFamily = formatSettings.fontFamily
      
      // 检查是否是头部信息
      const isHeaderInfo = lineData.content && (
        lineData.content.includes('时间') && lineData.content.includes('年') ||
        lineData.content.includes('地点') ||
        lineData.content.includes('询问/讯问人') ||
        lineData.content.includes('记录人') ||
        lineData.content.includes('被询问/讯问人') ||
        lineData.content.includes('身份证件种类') ||
        lineData.content.includes('现住址') ||
        lineData.content.includes('户籍所在地') ||
        lineData.content.includes('口头传唤')
      )
      
      // 判断是否为标题
      if (lineData.isTitle || lineData.content.includes('<h3')) {
        lineDiv.style.textIndent = '0'
        lineDiv.style.textAlign = 'center'
        lineDiv.style.borderBottom = 'none' // 标题不要横线
      } else if (isHeaderInfo) {
        // 头部信息不缩进
        lineDiv.style.textIndent = '0'
        lineDiv.style.textAlign = 'left'
        lineDiv.style.borderBottom = PrintUtils.getBottomLineStyle(formatSettings)
      } else {
        // 只有段落的第一行有缩进，后续行不缩进
        lineDiv.style.textIndent = lineData.isFirstLineOfParagraph ? `${formatSettings.paragraphIndent}em` : '0'
        lineDiv.style.textAlign = 'left'
        lineDiv.style.borderBottom = PrintUtils.getBottomLineStyle(formatSettings)
      }
      
      lineDiv.innerHTML = lineData.content || '&nbsp;'
      pageContent.push(lineDiv.outerHTML)
    })
    
    // 填充剩余空白行
    const remainingLines = totalLinesPerPage - pageLines.length
    for (let i = 0; i < remainingLines; i++) {
      const emptyLineDiv = PrintUtils.createEmptyLine(formatSettings)
      pageContent.push(emptyLineDiv.outerHTML)
    }
    
    return pageContent.join('')
  }

  function parseMarginBottomPx(marginBottom) {
    if (!marginBottom) return 0
    if (typeof marginBottom === 'number') return marginBottom
    if (marginBottom.endsWith('mm')) {
      // 1mm = 96/25.4 px
      return parseFloat(marginBottom) * 96 / 25.4
    } else if (marginBottom.endsWith('px')) {
      return parseFloat(marginBottom)
    } else if (marginBottom.endsWith('pt')) {
      // 1pt = 1.333px
      return parseFloat(marginBottom) * 1.333
    } else {
      // 默认按px处理
      return parseFloat(marginBottom)
    }
  }

  // 动态测量一行的实际高度（含margin/padding/border）
  function getActualLineHeight() {
    const testDiv = document.createElement('div')
    testDiv.className = 'record-line'
    testDiv.style.visibility = 'hidden'
    testDiv.style.position = 'absolute'
    testDiv.style.minHeight = `${parseFloat(formatSettings.fontSize) * parseFloat(formatSettings.lineHeight) * 1.33}px`
    testDiv.style.paddingBottom = '2px'
    testDiv.style.marginBottom = formatSettings.lineSpacing || '8mm'
    testDiv.style.lineHeight = formatSettings.lineHeight
    testDiv.style.fontSize = `${formatSettings.fontSize}pt`
    testDiv.style.fontFamily = formatSettings.fontFamily
    testDiv.innerHTML = '测试行'
    document.body.appendChild(testDiv)
    const style = window.getComputedStyle(testDiv)
    const height = testDiv.offsetHeight
    const marginBottom = parseFloat(style.marginBottom)
    document.body.removeChild(testDiv)
    return { height, marginBottom }
  }

  function paginateContent(content) {
    PrintUtils.removeHiddenContainer()
    const container = PrintUtils.createHiddenContainer(formatSettings)
    container.innerHTML = ''
    const html = content
    const lines = splitContentToLines(html)
    let pages = []
    let currentPageLines = []
    // 固定A4页面高度为1122px（297mm @ 96dpi）
    const maxHeight = 1122
    // 动态测量实际行高和margin-bottom
    const { height: realLineHeight, marginBottom: realMarginBottom } = getActualLineHeight()
    // 分页时每行都加margin-bottom，最后一行不加
    let accHeight = 0
    for (let i = 0; i < lines.length; i++) {
      // 如果当前页是最后一行，不加margin-bottom
      const isLastLineOfPage = currentPageLines.length === 0 ? false : (accHeight + realLineHeight > maxHeight)
      accHeight += realLineHeight
      if (!isLastLineOfPage) accHeight += realMarginBottom
      currentPageLines.push(lines[i])
      // 检查是否需要分页
      if (accHeight > maxHeight) {
        // 渲染当前页的所有行
        const pageContent = renderPageContent(currentPageLines, currentPageLines.length)
        pages.push(pageContent)
        currentPageLines = []
        accHeight = 0
      }
    }
    // 处理最后一页
    if (currentPageLines.length > 0 || pages.length === 0) {
      const pageContent = renderPageContent(currentPageLines, currentPageLines.length)
      pages.push(pageContent)
    }
    PrintUtils.removeHiddenContainer()
    return pages.length ? pages : [html]
  }

  return {
    paginateContent,
    splitContentToLines,
    renderPageContent
  }
}
